package com.yanqu.road.server.cmd.cross.union;

import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.pb.UnionPb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.Map;

@Cmd(code = Protocol.S_CROSS_TO_QUERY_UNION, desc = "跨服拜访商会")
public class CrossWatchUnionCmd extends AbstractCommand {

	private long userId;

	private long serverId;

	private String watchUnionId;

	private long watchServerId;

	private UnionInfo unionInfo;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		UnionProto.CrossUnionQueryToServerReqMsg reqMsg = UnionProto.CrossUnionQueryToServerReqMsg.parseFrom(packet.getBytes());
		userId = reqMsg.getUserId();
		serverId = reqMsg.getServerId();
		watchServerId = reqMsg.getWatchServerId();
		watchUnionId = reqMsg.getWatchUnionUid();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		unionInfo = CrossUnionMgr.getUnionInfo(watchUnionId);
		if(null == unionInfo){
			ret = GameErrorCode.E_UNION_NO_FOUND;
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		UnionProto.CrossUnionQueryFromServerRespMsg.Builder respMsg = UnionProto.CrossUnionQueryFromServerRespMsg.newBuilder();
		respMsg.setRet(ret);
		if(0 == ret){
			respMsg.setUserId(userId);
			respMsg.setServerId(serverId);
			respMsg.setUnion(UnionPb.parseUnionTempMsg(unionInfo));
			Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionInfo.getUnionUid());
			if (null != memberMap) {
				for (UnionMember member : memberMap.values()) {
					UnionProto.UnionMemberTempMsg.Builder memberMsg = UnionPb.parseUnionMemberTempMsg(member);
					if(null != memberMsg) {
						respMsg.addMemberList(memberMsg);
					}
				}
			}
		}
		YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_QUERY_UNION_RESP, respMsg);
		GamePlayerMgr.sendPacket(userId, pbMsg);
	}
}
